<!-- JobDetailView.vue -->
<template>
  <div id="app">
    <AppNavbar />

    <div class="job-detail-container">
      <div class="header">
        <h1>职位详情</h1>
        <button class="back-btn" @click="goBack">返回职位列表</button>
      </div>

      <div v-if="jobDetail" class="job-detail-content">
        <!-- 职位基本信息 -->
        <div class="job-basic-info">
          <div class="job-header">
            <h2 class="job-title">{{ jobDetail.positionName }}</h2>
            <span class="position-type">{{ getPositionTypeText(jobDetail.positionType) }}</span>
            <!-- 添加状态标签 -->
            <span
              :class="['status-tag', { 'status-active': jobDetail.status === 1, 'status-inactive': jobDetail.status === 0 }]"
            >
              {{ getJobStatusText(jobDetail.status) }}
            </span>
          </div>

          <div class="job-meta">
            <div class="salary">{{ jobDetail.salaryRange }}</div>
            <div class="location">{{ jobDetail.province }}</div>
            <div class="department">{{ jobDetail.department }}</div>
          </div>

          <!-- 标签 -->
          <div class="job-tags" v-if="jobDetail.tagList && jobDetail.tagList.length > 0">
            <span
              v-for="(tag, index) in jobDetail.tagList"
              :key="index"
              class="tag"
            >
              {{ tag }}
            </span>
          </div>
        </div>

        <!-- 职位描述 -->
        <div class="job-section">
          <h3>职位描述</h3>
          <div class="job-description">
            {{ jobDetail.jobDescription }}
          </div>
        </div>

        <!-- 能力要求 -->
        <div class="job-section">
          <h3>能力要求</h3>
          <div class="job-ability">
            {{ jobDetail.ability }}
          </div>
        </div>

        <!-- 操作按钮（仅候选人可见） -->
        <div v-if="isCandidate" class="job-actions">
          <button
            :class="['action-btn', 'collect-btn', { collected: isCollected }]"
            @click="toggleCollect"
          >
            <i :class="['iconfont', isCollected ? 'icon-shoucang' : 'icon-shoucang']"></i>
            <span>{{ isCollected ? '已收藏' : '收藏职位' }}</span>
            <i class="iconfont icon-star" :style="{
              marginLeft: '5px',
              color: isCollected ? '#ffcc00' : 'inherit'
            }"></i>
          </button>
          <!-- 根据职位状态和投递状态决定是否显示投递按钮 -->
          <button
            v-if="isDelivered || jobDetail.status === 1"
            :class="['action-btn', 'deliver-btn', { delivered: isDelivered }]"
            @click="deliverResume"
            :disabled="isDelivered"
          >
            {{ isDelivered ? '已投递' : '投递简历' }}
          </button>
        </div>
      </div>

      <div v-else class="loading">
        加载中...
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppNavbar from '../components/AppNavbar.vue'
import apiClient from '../utils/api.js'

export default {
  name: 'JobDetailView',
  components: {
    AppNavbar
  },
  setup () {
    const route = useRoute()
    const router = useRouter()
    const jobDetail = ref()
    const isCollected = ref(false)
    const isDelivered = ref(false)
    const isCandidate = ref(false)
    const positionId = route.params.positionId

    // 检查用户类型
    const checkUserType = () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr)
        isCandidate.value = userInfo.userType === 'candidate'
      }
    }

    // 获取职位详情
    const fetchJobDetail = async () => {
      try {
        const response = await apiClient.get(`/job/detail?positionId=${positionId}`)
        if (response.data.code === '200') {
          jobDetail.value = response.data.data
        } else {
          console.error('获取职位详情失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求职位详情出错:', error)
      }
    }

    // 获取收藏状态
    const fetchCollectStatus = async () => {
      if (!isCandidate.value) return

      try {
        const response = await apiClient.get(`/candidate/getCollectExist?positionId=${positionId}`)
        if (response.data.code === '200') {
          isCollected.value = response.data.data
        } else {
          console.error('获取收藏状态失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求收藏状态出错:', error)
      }
    }

    // 获取投递状态
    const fetchDeliveryStatus = async () => {
      if (!isCandidate.value) return

      try {
        const response = await apiClient.get(`/candidate/getDeliveryExist?positionId=${positionId}`)
        if (response.data.code === '200') {
          isDelivered.value = response.data.data
        } else {
          console.error('获取投递状态失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求投递状态出错:', error)
      }
      console.log('isDelivered:', isDelivered.value)
    }

    // 切换收藏状态
    const toggleCollect = async () => {
      try {
        let response
        if (isCollected.value) {
        // 取消收藏
          response = await apiClient.put(`/candidate/cancelCollectJob?positionId=${positionId}`)
        } else {
        // 收藏职位
          response = await apiClient.put(`/candidate/collectJob?positionId=${positionId}`)
        }

        if (response.data.code === '200') {
          isCollected.value = !isCollected.value
        } else {
          console.error('操作失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求出错:', error)
      }
    }

    // 投递简历
    const deliverResume = async () => {
      if (isDelivered.value) return

      try {
        const response = await apiClient.put(`/candidate/deliveryVitae?positionId=${positionId}`)
        if (response.data.code === '200') {
          isDelivered.value = true
        } else {
          console.error('投递失败:', response.data.msg)
        }
      } catch (error) {
        console.error('请求出错:', error)
      }
      console.log('isDelivered:', isDelivered.value)
    }

    // 返回职位列表
    const goBack = () => {
      router.push('/jobList')
    }

    // 获取职位类型文本
    const getPositionTypeText = (type) => {
      const typeMap = {
        'full-time': '全职',
        'part-time': '兼职',
        internship: '实习'
      }
      return typeMap[type] || type
    }

    // 获取职位状态文本
    const getJobStatusText = (status) => {
      const statusMap = {
        1: '招聘中',
        0: '已停招'
      }
      return statusMap[status] || '未知状态'
    }

    onMounted(() => {
      checkUserType()
      fetchJobDetail()
      fetchCollectStatus()
      fetchDeliveryStatus()
    })

    return {
      jobDetail,
      isCollected,
      isDelivered,
      isCandidate,
      toggleCollect,
      deliverResume,
      goBack,
      getPositionTypeText,
      getJobStatusText
    }
  }
}
</script>

<style scoped>
/* 引入阿里巴巴图标库 */
@import '//at.alicdn.com/t/c/font_5004955_vbgsf1v0zp8.css';

#app {
  background: linear-gradient(to right, #e0f7fa, #ffffff);
  min-height: 100vh;
  padding: 20px;
}

.job-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.header h1 {
  color: #1890ff;
  margin: 0;
}

.back-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  background-color: #1890ff;
  color: white;
  border: 1px solid #1890ff;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.job-detail-content {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.job-basic-info {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.job-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.job-title {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.position-type {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  background-color: #f9f0ff;
  color: #722ed1;
  white-space: nowrap;
}

/* 职位状态标签样式 */
.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-inactive {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.job-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.salary {
  font-size: 20px;
  font-weight: 500;
  color: #1890ff;
}

.location, .department {
  font-size: 16px;
  color: #666;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.job-section {
  margin-bottom: 30px;
  text-align: left; /* 添加这行使标题左对齐 */
}

.job-section h3 {
  color: #1890ff;
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  text-align: left; /* 确保标题左对齐 */
}

.job-description, .job-ability {
  color: #333;
  line-height: 1.6;
  white-space: pre-wrap;
  text-align: left; /* 内容左对齐 */
}

.job-actions {
  display: flex;
  gap: 15px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
  margin-top: 20px;
}

.action-btn {
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  border: 1px solid transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}

.collect-btn {
  background-color: #fff;
  color: #1890ff;
  border-color: #1890ff;
}

.collect-btn:hover:not(.collected) {
  background-color: #e6f7ff;
}

.collect-btn.collected {
  background-color: #1890ff;
  color: white;
}

.deliver-btn {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.deliver-btn:hover:not(.delivered) {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

.deliver-btn:disabled {
  background-color: #bfbfbf;
  cursor: not-allowed;
}

/* 收藏按钮图标样式 */
.collect-btn i {
  margin-right: 5px;
  font-size: 16px;
}

.collect-btn.collected i {
  color: #ffcc00;
}

.loading {
  text-align: center;
  padding: 40px;
  font-size: 16px;
  color: #999;
}

@media (max-width: 768px) {
  .job-detail-container {
    padding: 10px;
  }

  .job-detail-content {
    padding: 20px;
  }

  .job-meta {
    flex-direction: column;
    gap: 10px;
  }

  .job-actions {
    flex-direction: column;
  }

  .action-btn {
    width: 100%;
  }

  .header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
}
</style>
